package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.constant.WXConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static springfox.documentation.schema.ScalarType.URL;

@Service
public class UserServiceImpl implements UserService {
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatProperties weChatProperties;
    @Override
    public User login(UserLoginDTO userLoginDTO) throws JsonProcessingException {
        String openid = getOpenid(userLoginDTO.getCode());
        if (openid==null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.findUserByOpenid(openid);
        if (user==null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        return user;
    }
    /**
     * 根据授权码获取openid
     *  @param authCode
     *  @return
     *  @throws JsonProcessingException
     */
    private String getOpenid(String authCode) throws JsonProcessingException {
        HashMap<String, String> param = new HashMap<String, String>();
        param.put(WXConstant.APP_ID,weChatProperties.getAppid());
        param.put(WXConstant.APP_SECRET,weChatProperties.getSecret());
        param.put(WXConstant.JS_CDDE,authCode);
        param.put(WXConstant.GRANT_TYPE,"authorization_code");
        //通过HTTP工具类发送请求,获得反应状态
        String jsonResult = HttpClientUtil.doGet(URL, param);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,String> map = objectMapper.readValue(jsonResult, Map.class);
        return map.get(WXConstant.OPEN_ID);
    }
}
